package com.op.studyingliteapp.sender.ui.view.device;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;
import com.op.studyingliteapp.R;
import com.op.studyingliteapp.sender.Constants;
import com.op.studyingliteapp.sender.listener.OnChannelStatusListener;
import com.op.studyingliteapp.sender.runnable.DeviceScanRunnable;
import com.op.studyingliteapp.sender.runnable.SenderRunnable;
import com.op.util.ScreenSendUtils;
import com.op.util.network.NetworkUtils;
import io.netty.channel.ChannelHandlerContext;
import com.op.studyingliteapp.sender.Runtime;
import java.util.ArrayList;

public class DeviceScanDialog extends AlertDialog {
    private DeviceDisplayAdapter listAdapter;
    private SenderRunnable senderRunnable;
//    private Context context;
    private Activity activity;
    private UIhandle uIhandle;
    private  ProgressBar progressBar;

    public DeviceScanDialog(Activity activity) {
        super(activity);
        init(activity);

    }


    @Override
    public void show() {
        if (NetworkUtils.isWifiConnected(this.activity)) {
            super.show();
            new Thread(new DeviceScanRunnable(listAdapter, progressBar)).start();
        } else {
            Dialog dialog = new Builder(this.activity).setMessage("wifi状态不可用,是否打开无线设置?").setPositiveButton("确定", new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                    activity.startActivity(intent);


                }
            }).setNegativeButton("取消", new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).setTitle("wifi不可用").create();
            dialog.show();
        }

    }

    private void init(final Activity activity) {
        this.activity = activity;
        this.uIhandle = new UIhandle();
        LayoutInflater layoutInflater = LayoutInflater.from(activity);
        View view = layoutInflater.inflate(R.layout.dialog_device_scan,
                null);
        Button button = (Button) view.findViewById(R.id.get_devices);
        this.progressBar =(ProgressBar)view.findViewById(R.id.device_scan_bar);

        ListView deviceListView = (ListView) view.findViewById(R.id.device_list);



        this.listAdapter = new DeviceDisplayAdapter(activity, R.layout.device_item_row, new ArrayList<DeviceDisplay>());

        deviceListView.setAdapter(listAdapter);
        button.setOnClickListener(new View.OnClickListener() {
            //
            @Override
            public void onClick(View v) {
                listAdapter.clear();
                new Thread(new DeviceScanRunnable(listAdapter,progressBar)).start();


            }
        });
        deviceListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                DeviceDisplay deviceDisplay = listAdapter.getItem(position);

                initRunnable(deviceDisplay);
                new Thread(senderRunnable).start();


            }
        });
        DeviceScanDialog.this.setView(view, 0, 0, 0, 0);
        if (!Runtime.isOffLine()) {
            DeviceScanDialog.this.setButton(BUTTON_NEGATIVE, "关闭连接", new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (!Runtime.closeChannel()) {
                        Toast.makeText(activity,"连接已经关闭",Toast.LENGTH_LONG).show();
                    }

                }
            });
        }




    }

    private void initRunnable(final DeviceDisplay deviceDisplay) {

        senderRunnable = new SenderRunnable(deviceDisplay.getIp(), Constants.studentPort);
        senderRunnable.setOnChannelStatusListener(new OnChannelStatusListener() {
            @Override
            public void channelActive(ChannelHandlerContext context) {
                Runtime.setContext(context);
                Runtime.setIp(deviceDisplay.getIp());
                uIhandle.sendEmptyMessage(Constants.CHANNEL_ACTIVE);
            }

            @Override
            public void channelInactive(ChannelHandlerContext context) {
                Runtime.setContext(null);
                Runtime.setIp(null);
                uIhandle.sendEmptyMessage(Constants.CHANNEL_INACTIVE);

            }

            @Override
            public void channelRead(ChannelHandlerContext context, Object msg) {
//                ByteBuf byteBuf =(ByteBuf)msg;
//                Log.i("DeviceScanDialog", String.valueOf(byteBuf.readInt()));
//                switch (byteBuf.readInt()) {
//
//                    case View.GONE:
//
//
//                }

            }

            @Override
            public void channelReadComplete(ChannelHandlerContext context) {

            }

            @Override
            public void userEventTriggered(ChannelHandlerContext context, Object evt) {

            }

            @Override
            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                Runtime.setContext(null);
                Runtime.setIp(null);
                uIhandle.sendEmptyMessage(Constants.EXCEPTION_CAUGHT);
            }
        });


    }

    private class UIhandle extends Handler {


        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constants.CHANNEL_ACTIVE:

//                    Runtime.play();

                    Runtime.refreshStatus();
                    DeviceScanDialog.this.dismiss();
                    break;
                case Constants.CHANNEL_INACTIVE:
                    Toast.makeText(activity, "连接已经断开", Toast.LENGTH_LONG).show();
                    Runtime.setContext(null);
                    Runtime.setIp(null);
//                    Runtime.pause();
                    Runtime.refreshStatus();

                    break;
            }


        }

    }
}


